package com.litengsoft.lianmeng.service.impl;

import com.litengsoft.lianmeng.common.HttpUtils;
import com.litengsoft.lianmeng.domain.WebWXResponse;
import com.litengsoft.lianmeng.service.LocalCacheService;
import com.litengsoft.lianmeng.service.LoginService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.cookie.Cookie;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 登录服务
 */
@Slf4j
@Service("loginService")
public class LoginServiceImpl implements LoginService {

    @Value("${web_wx_login_uuid_url}")
    private String loginUuidUrl;

    @Value("${web_wx_qrcode_url}")
    private String qrCodeUrl;

    @Value("${web_wx_login_status_url}")
    private String loginStatusUrl;

    @Resource(name = "localCacheService")
    private LocalCacheService localCacheService;


    /**
     * 获得uuid
     *
     * @return
     */
    @Override
    public String getWebWXUuid() {
        String url = loginUuidUrl + System.currentTimeMillis();
        try {
            String returnStr = HttpUtils.sendHttpGet(url);
            WebWXResponse webWXResponse = new WebWXResponse(returnStr);
            return webWXResponse.getUuid();
        } catch (Exception e) {
            log.error("获取登录uuid失败", e);
        }
        return null;
    }

    /**
     * 根据uuid获取登录二维码
     *
     * @param uuid
     * @return
     */
    @Override
    public String getQRCode(String uuid) {
        String url = String.format(qrCodeUrl, uuid);
        try {
            String returnStr = HttpUtils.sendHttpGet(url);
            log.info(returnStr);
            return returnStr;
        } catch (Exception e) {
            log.error("根据uuid获取二维码失败,uuid:{}", uuid);
        }
        return null;
    }

    /**
     * 获取登录状态
     * 需要轮询
     *
     * @param uuid
     * @return
     */
    @Override
    public String getLoginStatus(String uuid) {
        log.info("获取登录状态开始，uuid：{}", uuid);
        int i = 0;
        while (true) {
            if (i == 200) {
                break;
            }
            String url = String.format(loginStatusUrl, uuid, System.currentTimeMillis());
            try {
                String s = HttpUtils.sendHttpGet(url);
                WebWXResponse wxResponse = new WebWXResponse(s);
                if ("201".equals(wxResponse.getCode())) {
                    log.info("已扫码，uuid：{}", uuid);
                }
                if (StringUtils.isNotBlank(wxResponse.getRedirectUri())) {
                    log.info("登录成功，uuid：{}", uuid);
                    return wxResponse.getRedirectUri();
                }
                i++;
                //暂停500ms
                Thread.sleep(500);
            } catch (SocketTimeoutException e) {

            } catch (Exception e) {
                log.error("获取登录状态失败，uuid：{}", uuid, e);
            }
        }
        return null;
    }

    /**
     * 获取uin与sid
     *
     * @param url
     */
    @Override
    public void getLoginCookies(String url) {
        log.info("获得uid，sid链接：{}", url);
        try {
            List<Cookie> cookies = HttpUtils.sendHttpGetAndGetCookie(url, null, null);
            if (cookies == null) {
                log.error("获取登录cookie为空，url:{}", url);
                return;
            }
            Map<String, String> map = new HashMap<>();
            for (Cookie c : cookies) {
                map.put(c.getName(), c.getValue());
            }
            localCacheService.putAll(map);
        } catch (Exception e) {
            log.error("获取uin与sid失败，url：{}", url, e);
        }
    }

}
